//
//  AppDelegate.swift
//  LeTu
//
//  Created by gy on 2023/11/23.
//

import UIKit
import CoreData
import IQKeyboardManagerSwift
import AVFoundation

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    // 屏幕旋转
    var isForceLandscape: Bool = false
    var isForcePortrait: Bool = true

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // 配置键盘
        IQKeyboardManager.shared.enable = true
            
        kUMengManager.initUMCommon()
        kUMengManager.initUMSocial()
                
        // 初始化窗口
        initWindow()
        
        kAdsManager.initBUAds()
        
        // 处理未完成的交易
        ApplePayManager.shared.restoreTransactions()
        
        return true
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        AppAudioManager.shared.setPlaybackSession()
    }
    
    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "LeTu")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

// MARK: - 初始化窗口
extension AppDelegate {
    
    /// 初始化窗口
    func initWindow() {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        setRootVC()
        
        // 配置全局样式
        AppThemeManager.shared.configGlobalAppearances()
        
        // 开启灰度
        //kAppThemeManager.isGreyOut = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(setRootVC), name: NSNotification.Name("ResetRootVC"), object: nil)
    }
    @objc func setRootVC() {
        window?.rootViewController = kAppThemeManager.generateWindowRootViewController()
    }
    
}

// MARK: - sdk 回调
extension AppDelegate {
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        
        if UMSocialManager.default().handleOpen(url, options: options) {
            return true
        }
        
        return false
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        if UMSocialManager.default().handleOpen(url, sourceApplication: sourceApplication, annotation: annotation) {
            return true
        }
        
        return false
    }
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        if UMSocialManager.default().handleOpen(url) {
            return true
        }
        
        return false
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        
        if UMSocialManager.default().handleUniversalLink(userActivity, options: nil) {
            return true
        }
        
        return false
    }
    
}

// MARK: - 屏幕旋转
extension AppDelegate {
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        
        if isForceLandscape {
            //这里设置允许横屏的类型
            return .landscapeRight
        }else if isForcePortrait {
            return .portrait
        }
        return [.portrait,.landscapeRight,.landscapeLeft]
    }
    
}



